package com.study.shiro.controller;

import com.study.shiro.entity.UserVo;
import com.study.shiro.util.RepDate;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 不需要登录
 *
 * @author huanggy
 * @date 2020/2/10 12:29
 */
@RequestMapping("/pub")
@RestController
public class PubController {

    @GetMapping("/needLogin")
    public RepDate needLogin() {
        return RepDate.error("请登录");
    }

    @GetMapping("/noPermission")
    public RepDate noPermission() {
        return RepDate.error("请联系管理员分配权限");
    }

    @GetMapping("/index")
    public RepDate index() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add("数据" + i);
        }
        return RepDate.success(list, "请求成功");
    }

    @PostMapping("/login")
    public RepDate login(@RequestBody UserVo userVo) {
        HashMap<String, Object> map = new HashMap<>(2);
        Subject subject = SecurityUtils.getSubject();

        try {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userVo.getUsername(), userVo.getPassword());
            subject.login(usernamePasswordToken);
        } catch (Exception e) {
            map.put("msg", "用户名或密码不正确");
            return RepDate.success(map);
        }

        map.put("msg", "登录成功");
        map.put("session_id", subject.getSession().getId());

        return RepDate.success(map, "请求成功");
    }

    @GetMapping("/logout")
    public RepDate logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return RepDate.success("退出成功");
    }

}
